import os
import sys
import logging
import webbrowser
import threading
import time

# 添加项目根目录到Python路径
if getattr(sys, 'frozen', False):
    # 打包后的环境
    base_path = sys._MEIPASS
    PROJECT_ROOT = os.path.dirname(base_path)
    print(f"📦 打包环境: base_path={base_path}, PROJECT_ROOT={PROJECT_ROOT}")
else:
    # 开发环境
    PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))
    print(f"🔧 开发环境: PROJECT_ROOT={PROJECT_ROOT}")

# 添加backend目录到Python路径
backend_path = os.path.join(PROJECT_ROOT, 'backend')
if backend_path not in sys.path:
    sys.path.insert(0, backend_path)
    print(f"✅ 添加backend路径: {backend_path}")

print("=" * 60)
print("🎨 小说转漫画桌面版启动中...")
print("📡 服务地址: http://localhost:5000")
print(f"📁 项目根目录: {PROJECT_ROOT}")
print("✨ 双击此程序即可使用，关闭窗口即可退出")
print("=" * 60)

# 现在导入Flask应用
try:
    from app import app
    print("✅ 成功导入Flask应用")
    
    # 确保必要的目录存在
    from app import IMAGE_DIR
    os.makedirs(IMAGE_DIR, exist_ok=True)
    print(f"🖼️ 图片目录: {IMAGE_DIR}")
    
except ImportError as e:
    print(f"❌ 导入失败: {e}")
    print(f"Python路径: {sys.path}")
    input("按回车键退出...")
    sys.exit(1)

def open_browser():
    """在浏览器中打开应用"""
    time.sleep(3)  # 等待服务器启动
    webbrowser.open('http://localhost:5000')

if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO)
    
    # 在后台线程中打开浏览器
    browser_thread = threading.Thread(target=open_browser)
    browser_thread.daemon = True
    browser_thread.start()
    
    # 启动Flask应用
    try:
        app.run(debug=False, host='0.0.0.0', port=5000, use_reloader=False)
    except Exception as e:
        print(f"❌ 启动服务器失败: {e}")
        input("按回车键退出...")